package com.group.flagtivities;

import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.group.flagtivities.LikeView.OnLikeListener;

public class Detail extends Activity implements OnClickListener, OnLikeListener {
	
	private RelativeLayout deleteContainer;
	private ProgressBar deleteIndicator;
	private TextView creator;
	private TextView attending;
	private TextView description;
	private TextView room;
	private TextView title;
	private TextView type;
	private TextView start;
	private TextView end;
	private LikeView likeView;
	private Button close;
	private Button delete;
	private Button rsvp;
	
	private Bundle details;
	private ArrayList<Integer> mLikes = new ArrayList<Integer>();
	private ArrayList<Integer> mRSVPs = new ArrayList<Integer>();
	private SQLiteDatabase database;
	private SQLiteDatabase databaseRSVPs;
	
	private int user_id;
	private int type_id;
	private int activity_id;
	private int owner;
	private int dislikes;
	private int likes;
	private int RSVPs;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail);
                
        findViews();
        configure();
        setTexts();
        setLikes();
        setDatabases();
        populateFromDatabase(database, "likes", mLikes);
        populateFromDatabase(databaseRSVPs, "rsvp", mRSVPs);
        setRSVPability();
        
        TextUtil.setFont((ViewGroup) findViewById(R.id.detail), getAssets());
    }

	private void removeFlagtivity() {
		for (FlagtivityObject flag : Flagtivities.FlagtivityList) {
			if (flag.activity_id == activity_id) {
				Flagtivities.FlagtivityList.remove(flag);
				break;
			}
		}
	}
	
	private void setDatabases() {
		LikesOpenHelper likesHelper = new LikesOpenHelper(this);
        database = likesHelper.getWritableDatabase();
        RSVPOpenHelper RSVPHelper = new RSVPOpenHelper(this);
        databaseRSVPs = RSVPHelper.getWritableDatabase();
	}
	
	private void populateFromDatabase(SQLiteDatabase database, String table, ArrayList<Integer> list) {
		Cursor cursor = database.rawQuery("SELECT activity_id FROM " + table + " WHERE user_id = ?", new String[]{ ""+user_id });
		while (cursor.moveToNext()) {
			list.add(cursor.getInt(0));
		}
	}
	
	private void setRSVPability() {
		if (mRSVPs.contains(activity_id)) {
        	Button rsvp = (Button) findViewById(R.id.rsvp);
        	rsvp.setText("unRSVP");
        }
	}
	
	private void findViews() {
		deleteContainer = (RelativeLayout) findViewById(R.id.deleteContainer);
        deleteIndicator = (ProgressBar) findViewById(R.id.deleteIndicator);
        type = (TextView) findViewById(R.id.type);
        creator = (TextView) findViewById(R.id.creator);
        attending = (TextView) findViewById(R.id.attending);
        description = (TextView) findViewById(R.id.description);
        room = (TextView) findViewById(R.id.room);
        title = (TextView) findViewById(R.id.title);
        start = (TextView) findViewById(R.id.start);
        end = (TextView) findViewById(R.id.end);
        likeView = (LikeView) findViewById(R.id.likeView);
        close = (Button) findViewById(R.id.close);
        delete = (Button) findViewById(R.id.delete);
        rsvp = (Button) findViewById(R.id.rsvp);
	}
	
	private void configure() {
		details = getIntent().getBundleExtra("Details");
        activity_id = details.getInt("Activity_ID");
        owner = details.getInt("Owner");
        dislikes = details.getInt("Dislikes");
        likes = details.getInt("Likes");
        RSVPs = details.getInt("Attending");
        type_id = details.getInt("Type");
        
        user_id = Flagtivities.user_id;
        if (user_id == owner) {
        	deleteContainer.setVisibility(View.VISIBLE);
        }
	}
	
	private void setTexts() {
		String creatorName = creatorName(Flagtivities.FriendList, owner);
        if (creatorName != null) {
        	creator.setText(styleText("Created By: ", creatorName));
        	creator.setVisibility(View.VISIBLE);
        }
        
        attending.setText("Attending: " + RSVPs);
        description.setText(styleText("Description:", details.getString("Description")));
        room.setText(styleText("Room:", details.getString("Room")));
        title.setText(styleText("Title:", details.getString("Title")));
        
        start.setText(styleText("Start:", parseTime(Long.parseLong(details.getString("Start")))));
        end.setText(styleText("End:", parseTime(Long.parseLong(details.getString("End")))));
        type.setText(styleType());
	}
	
	private void setLikes() {
		likeView.setOnLikeListener(this);
        likeView.setDislikes(dislikes);
        likeView.setLikes(likes);
        likeView.setProgressBar();
	}
	
	private String creatorName(ArrayList<FriendObject> friends, int friend_id) {
		for (FriendObject friend : friends) {
			if (friend.friend_id == friend_id) return friend.first + " " + friend.last;
		}
		
		return null;
	}
	
	private String parseTime(long time) {
		Date date = new Date(time * 1000);
		
		int year = date.getYear() + 1900;
		int month = date.getMonth();
		int weekday = date.getDay();
		int day = date.getDate();
		int hour = date.getHours();
		int min = date.getMinutes();
		
		String dateString = parseDay(weekday) + ", " + parseMonth(month) + " " + day + ", " + year + " @ " + parseHour(hour) + ":" + parseMin(min) + " " + parseAMPM(hour);
		
		return dateString;
	}
	
	private String parseMin(int min) {
		String minString = "";
		
		if (min < 10) minString = "0" + min;
		else minString = "" + min;
		
		return minString;
	}
	
	private String parseAMPM(int hour) {		
		if (hour >= 12) return "PM";
		else return "AM";
	}
	
	private String parseHour(int hour) {
		String hourString = "";
		
		if (hour > 12) hourString = "" + (hour - 12);
		else hourString = "" + hour;
		
		if (hour == 0) hourString = "12";
		
		return hourString;
	}
	
	private String parseMonth(int month) {
		String monthString = "";
		switch(month) {
		case 0:
			monthString = "January";
			break;
		case 1:
			monthString = "February";
			break;
		case 2:
			monthString = "March";
			break;
		case 3:
			monthString = "April";
			break;
		case 4:
			monthString = "May";
			break;
		case 5:
			monthString = "June";
			break;
		case 6:
			monthString = "July";
			break;
		case 7:
			monthString = "August";
			break;
		case 8:
			monthString = "September";
			break;
		case 9:
			monthString = "October";
			break;
		case 10:
			monthString = "November";
			break;
		case 11:
			monthString = "December";
			break;
		}
		
		return monthString;
	}
	
	private String parseDay(int day) {
		String dayString = "";
		switch(day) {
		case 0:
			dayString = "Sun";
			break;
		case 1:
			dayString = "Mon";
			break;
		case 2:
			dayString = "Tues";
			break;
		case 3:
			dayString = "Wed";
			break;
		case 4:
			dayString = "Thur";
			break;
		case 5:
			dayString = "Fri";
			break;
		case 6:
			dayString = "Sat";
			break;
		}
		
		return dayString;
	}

	@Override
	protected void onDestroy() {
		database.close();
		databaseRSVPs.close();
		
		super.onDestroy();
	}

	private SpannableStringBuilder styleText(String label, String text) {
		SpannableStringBuilder sb = new SpannableStringBuilder();
		SpannableString s = new SpannableString(label);
		s.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.red_light)), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		sb.append(s);
		sb.append(" " + text);

		return sb;
	}
	
	private SpannableStringBuilder styleType() {
		SpannableStringBuilder sb = new SpannableStringBuilder();
		SpannableString s = new SpannableString("Type: ");
		s.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.red_light)), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		sb.append(s);
		
		SpannableString text = new SpannableString("");
		
		switch(type_id) {
		case TypePicker.ATHLETICS:
			text = new SpannableString("Athletics");
			text.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.red_light)), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			break;
		case TypePicker.COMPUTER_SCIENCE:
			text = new SpannableString("Computer Science");
			text.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.orange_light)), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			break;
		case TypePicker.FINE_ARTS:
			text = new SpannableString("Fine Arts");
			text.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.yellow_light)), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			break;
		case TypePicker.FOREIGN_LANGUAGE:
			text = new SpannableString("Foreign Language");
			text.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.green_light)), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			break;
		case TypePicker.HUMANITIES:
			text = new SpannableString("Humanities");
			text.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.blue_light)), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			break;
		case TypePicker.MATHEMATICS:
			text = new SpannableString("Mathematics");
			text.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.indigo_light)), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			break;
		case TypePicker.SOCIAL:
			text = new SpannableString("Social");
			text.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.violet_light)), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			break;
		}
		
		sb.append(text);
		return sb;
	}
	
	@Override
	public void onClick(View view) {
		switch(view.getId()) {
		case R.id.close:
			finish();
			break;
		case R.id.rsvp:
			if (rsvp.getText().toString().equalsIgnoreCase("RSVP")) {
				RSVPs++;
				rsvp.setText("unRSVP");
				WebUtil.RSVPActivity(activity_id);
				mRSVPs.add(activity_id);
				databaseRSVPs.execSQL("INSERT INTO rsvp VALUES ( null, ?, ?)", new String[]{""+user_id, ""+activity_id});
			}else {
				RSVPs--;
				rsvp.setText("RSVP");
				WebUtil.unRSVPActivity(activity_id);
				mRSVPs.remove(new Integer(activity_id));
				databaseRSVPs.execSQL("DELETE FROM rsvp WHERE activity_id = ?", new String[]{""+activity_id});
			}
			attending.setText("Attending: " + RSVPs);
			break;
		case R.id.delete:
			removeFlagtivity();
			
			setInteractability(false);
			delete.setTextColor(Color.GRAY);
			
			Timer t = new Timer();
			t.schedule(new TimerTask() {
				public void run() {
					WebUtil.deleteActivity(activity_id);
					finish();
				}
			}, 3000);
			break;
		}
	}
	
	private void setInteractability(boolean isInteractable) {
		close.setEnabled(isInteractable ? true : false);
		likeView.setClickable(isInteractable ? true : false);
		delete.setEnabled(isInteractable ? true : false);
		rsvp.setEnabled(isInteractable ? true : false);
		deleteIndicator.setVisibility(isInteractable ? View.GONE : View.VISIBLE);
	}

	@Override
	public void onDislike() {
		if (!mLikes.contains(activity_id)) {
			dislikes++;
			likeView.setDislikes(dislikes);
			likeView.setProgressBar();
			WebUtil.dislikeActivity(activity_id);
			mLikes.add(activity_id);
			database.execSQL("INSERT INTO likes VALUES ( null, ?, ?)", new String[]{""+user_id, ""+activity_id});
		}
	}

	@Override
	public void onLike() {
		if (!mLikes.contains(activity_id)) {
			likes++;
			likeView.setLikes(likes);
			likeView.setProgressBar();
			WebUtil.likeActivity(activity_id);
			mLikes.add(activity_id);
			database.execSQL("INSERT INTO likes VALUES ( null, ?, ?)", new String[]{""+user_id, ""+activity_id});
		}
	}
}
